package zzps.exeed.web.handle;

import jakarta.servlet.http.HttpServletResponse;
import zzps.exeed.kernel.tool.FastList;
import zzps.exeed.web.Context;
import zzps.exeed.web.handle.argument.HandlerMethodArgumentResolver;
import zzps.exeed.web.http.HttpMethod;
import zzps.exeed.web.route.Route;
import zzps.exeed.web.route.RouteTable;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class HandlerManager {
    private static HandlerManager handlerManager = new HandlerManager();
    private RouteTable routeTable = new RouteTable();
    private List<Filter> filterChain = new FastList<>(Filter.class,64);

    private List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
     public static HandlerManager get(){
         return handlerManager;
     }
    private HandlerManager() {
    }

    public void handle(Context context) throws Throwable{
        String path = context.path();
        Route route = routeTable.match(path, context.method());
        if (route == null){
            context.status(404);
            context.output(context.path()+"找不到");
            return;
        }
        Handler handler = route.getHandler();
        if (filterChain.isEmpty()){
            handler.handle(context);
        }else{
            new FilterChainImpl(handler,filterChain).doFilter(context);
        }
    }

    public void addHandler(String path,Handler handler){
        Route route = new Route(path, HttpMethod.values(), handler);
        routeTable.add(route);
    }
    public void addRoute(Route route){
        routeTable.add(route);
    }
    public void addFilter(Filter filter){
        filterChain.add(filter);
    }

    public void addArgumentResolver(HandlerMethodArgumentResolver resolver){
        argumentResolvers.add(resolver);
    }
    public List<HandlerMethodArgumentResolver> getArgumentResolvers(){
         return argumentResolvers;
    }

}
